import React, { Component } from 'react';
import { Grid, SearchBar, Carousel } from 'antd-mobile';
import PubSub from 'pubsub-js';
import {
    getDeviceId,
    getRankAlbums,
    getAlbumGroup,
    getBindDevice,
    saveDeviceInfo
} from '../utils';
import RecommendHeader from '../components/RecommendHeader';
import CategoryButton from '../components/CategoryButton';
import HotRankingAlbum from '../components/HotRankingAlbum';
import { CACHE_TMP_SEARCH_AUDIOS, CACHE_TMP_SEARCH_ALBUMS,CACHE_TMP_SEARCH_TAB_INDEX, CACHE_TMP_RECOMMAND_GROUP, CACHE_TMP_RANK_ALBUM } from '../config';

/**
 * 首页推荐
 */
class HomeRecommend extends Component {

    constructor(props, context) {
        super(props, context);

        this.handleClickMore = this.handleClickMore.bind(this);
        this.handleClickCategory = this.handleClickCategory.bind(this);

        const banners = JSON.parse(localStorage.getItem('banner_list'));
        const company_name = localStorage.getItem('company_name');
        this.width = document.documentElement.clientWidth;
        const cols = 3;
        this.itemWidth = (this.width) / cols;

        const albumGroupString = sessionStorage.getItem(CACHE_TMP_RECOMMAND_GROUP);
        const rankAlbumsString = sessionStorage.getItem(CACHE_TMP_RANK_ALBUM);
        let rankAlbums = [];
        let albumGroup = [];
        if (albumGroupString) {
            albumGroup = JSON.parse(albumGroupString);
        }
        if (rankAlbumsString) {
            rankAlbums = JSON.parse(rankAlbumsString);
        }
        
        this.state = {
            banner: banners,
            albumGroup: albumGroup,
            rankAlbums: rankAlbums,
            height: 0,
            company_name: company_name,
            cols: cols,
        };
        this.clearInValidData();
    }
    clearInValidData() {
        sessionStorage.removeItem('category');
        sessionStorage.removeItem('scrollY');
        sessionStorage.removeItem('category_id');
        sessionStorage.removeItem('albums');
        sessionStorage.removeItem(CACHE_TMP_SEARCH_AUDIOS);
        sessionStorage.removeItem(CACHE_TMP_SEARCH_ALBUMS);
        sessionStorage.removeItem(CACHE_TMP_SEARCH_TAB_INDEX);
    }

    componentDidMount() {
        document.title = localStorage.getItem('device_name');
        this._isMounted = true;
        getBindDevice((result) => {
            if (result.errcode === 0) {
                const deviceItem = result.data;
                saveDeviceInfo(deviceItem)
                PubSub.publish('showTips', !!deviceItem);
            };
            getAlbumGroup().then((result) => {
                if (this._isMounted) {
                    if (result.errcode === 0) {
                        this.setState({
                            albumGroup: result.data
                        });
                        sessionStorage.setItem(CACHE_TMP_RECOMMAND_GROUP, JSON.stringify(result.data));
                    }
                }
            });
        });
        getRankAlbums((result) => {
            if (this._isMounted) {
                if (result.errcode === 0) {
                    this.setState({
                        rankAlbums: result.data
                    });
                    sessionStorage.setItem(CACHE_TMP_RANK_ALBUM, JSON.stringify(result.data));
                }
            }
        });
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    // 搜索
    handleClickSearch() {
        this.props.history.push({
            pathname: '/search',
        });
    }

    // 类别
    handleClickCategory(index) {
        this.props.history.push({
            pathname: '/tabs',
            category: index,
        });
    }

    // 广告栏
    handleClickBanner(index) {
        console.log(`index:${index}`);
        const album_id = this.state.banner[index].album_id;
        this.props.history.push({
            pathname: '/album',
            device_id: getDeviceId(),
            album: { album_id: album_id, img_url: '', name: '' }
        });
    }

    // 点击显示分组的专辑
    handleClickGroupAlbum(groupIndex, albumIndex) {
        const album = this.state.albumGroup[groupIndex].album_list[albumIndex];
        this.props.history.push({
            pathname: '/album',
            device_id: getDeviceId(),
            album: album
        });
    }

    handleRankingAlbum(index) {
        const album = this.state.rankAlbums[index];
        this.props.history.push({
            pathname: '/album',
            device_id: getDeviceId(),
            album: album
        });
    }

    // 点击更多
    handleClickMore(groupId) {
        if (groupId === -1) {
            this.props.history.push({ pathname: '/rank_album' });
        } else {
            const groupList = this.state.albumGroup;
            let group_name = localStorage.getItem('device_name');
            for (let index = 0; index < groupList.length; index++) {
                const item = groupList[index];
                if (parseInt(item.album_group_id, 10) === parseInt(groupId, 10)) {
                    group_name = item.album_group_name;
                    break;
                }
            }
            this.props.history.push({
                pathname: '/album_group',
                groupId: groupId,
                group_name: group_name
            })
        }
    }

    render() {
        const bottomLine = <div style={{ background: '#F5F5F5', height: '0.4rem', width: '100%' }} />
        return (
            <div style={{ overflow: 'scroll', width: '100%', height: '100%', background: '#ffffff' }}>
                <div onClick={this.handleClickSearch.bind(this)}>
                    <SearchBar disabled defaultValue='' placeholder='搜索专辑、故事、歌曲' />
                </div>
                <CategoryButton handleClickCategory={this.handleClickCategory} />
                <Carousel
                    autoplay
                    infinite
                    autoplayInterval={4000}
                >
                    {this.state.banner.map((item, index) => (
                        <a
                            key={index}
                            style={{ display: 'block', width: '100%' }}
                            onClick={this.handleClickBanner.bind(this, index)}>
                            <img
                                key={'' + index}
                                src={item.img_name}
                                alt=''
                                style={{ width: '100%', verticalAlign: 'top' }}
                                onLoad={() => {
                                    window.dispatchEvent(new Event('resize'));
                                    document.scrollingElement.scrollTop = 0;
                                }}
                            />
                        </a>
                    ))}
                </Carousel>

                {
                    this.state.albumGroup.map((item, i) => {
                        return (
                            <div key={'' + i}>
                                <RecommendHeader imageUrl={item.album_group_url} groupId={item.album_group_id} title={item.album_group_name} handleClickMore={this.handleClickMore} />
                                <Grid
                                    data={item.album_list}
                                    hasLine={false}
                                    columnNum={this.state.cols}
                                    square={true}
                                    itemStyle={{ height: this.itemWidth + 5 }}
                                    renderItem={(album, index) => (
                                        <div style={{ padding: '3px', lineHeight: 1.2 }} onClick={this.handleClickGroupAlbum.bind(this, i, index)}>
                                            <div style={{ width: '100%', height: this.itemWidth - 20 }}>
                                                <img src={album.img_url} style={{ borderRadius: '5px', width: this.itemWidth - 15, height: this.itemWidth - 15 }} alt="" />
                                            </div>
                                            <div style={{
                                                color: '#616161', fontSize: '11px', lineHeight: 1.2, marginTop: 6,
                                                textAlign: 'center',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap'
                                            }}>
                                                <span>{album.name}</span>
                                            </div>
                                        </div>
                                    )}
                                />
                                {bottomLine}
                            </div>
                        )
                    })
                }

                <RecommendHeader title={"热门排行"} groupId={-1} handleClickMore={this.handleClickMore} />
                <div>
                    {
                        this.state.rankAlbums.map((album, index) => {
                            return (
                                <HotRankingAlbum
                                    key={"" + index}
                                    index={index}
                                    album={album}
                                    handleRankingAlbum={this.handleRankingAlbum.bind(this, index)} />
                            )
                        })
                    }

                </div>

                <div style={{
                    background: '#F5F5F5', height: '100px', width: '100%', fontSize: '13px',
                    justifyContent: 'center', alignItems: 'center', display: 'flex',
                    marginBottom: 0
                }}>
                    <p>以上内容来自{this.state.company_name}的智能推荐</p>
                </div>

            </div>
        );
    }
}


export default HomeRecommend;
